package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaweicloud.sdk.iotda.v5.model.ServiceCapability;
import com.huaweicloud.sdk.iotda.v5.model.ServiceProperty;
import com.huaweicloud.sdk.iotda.v5.model.ShowDeviceResponse;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.common.utils.huawei.HuaweiIotUtil;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.MemberElderDto;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.nursing.vo.DeviceDataGraphVo;
import com.zzyl.nursing.vo.DevicePropertyStatusInfo;
import com.zzyl.nursing.vo.LoginVo;
import com.zzyl.nursing.vo.MemberElderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

/**
 * 老人家属Service业务层处理
 *
 * @author ruoyi
 * @date 2024-09-19
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {
    @Autowired
    private FamilyMemberMapper familyMemberMapper;
    @Autowired
    private WechatService wechatService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private FamilyMemberElderMapper familyMemberElderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private RoomMapper roomMapper;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Autowired
    private HuaweiIotUtil huaweiIotUtil;

    static List<String> DEFAULT_NICK_NAME = ListUtil.of(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝");

    /**
     * 小程序登录
     *
     * @param dto
     * @return
     */
    @Override
    public LoginVo login(UserLoginRequestDto dto) {

        //1.获取openid(调用微信的接口获取) ***
        String openid = wechatService.getOpenid(dto.getCode());

        //2.根据openid查询用户
        LambdaQueryWrapper<FamilyMember> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FamilyMember::getOpenId, openid);
        FamilyMember familyMember = getOne(queryWrapper);

        //3.判断用户是否存在，用户不存在，就构建用户
        if (ObjectUtil.isEmpty(familyMember)) {
            /*familyMember = new FamilyMember();
            familyMember.setOpenId(openid);*/
            familyMember = FamilyMember.builder()
                    .openId(openid)
                    .build();
        }

        //4.获取用户的手机号（调用微信的接口获取）***
        String phone = wechatService.getPhone(dto.getPhoneCode());

        //5. 新增或修改用户
        inserOrUpdateFamilyMember(familyMember, phone);

        //6. 把用户的信息封装到token,返回
        Map<String, Object> claims = new HashMap<>();
        claims.put("username", familyMember.getName());
        claims.put("userId", familyMember.getId());
        String token = tokenService.createToken(claims);

        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setNickName(familyMember.getName());

        return loginVo;
    }

    /**
     * 绑定家人
     *
     * @param memberElderDto
     */
    @Transactional
    @Override
    public void bindFamily(MemberElderDto memberElderDto) {
        //根据老人idcard查询老人
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<Elder>()
                .eq(Elder::getIdCardNo, memberElderDto.getIdCard())
                .eq(Elder::getStatus, 1);
        Elder elder = elderMapper.selectOne(queryWrapper);
        if (ObjectUtil.isEmpty(elder)) {
            throw new BaseException("老人不存在，请重新输入");
        }
        //从userthreadlocal中获取userid
        Long userId = UserThreadLocal.getUserId();

        FamilyMember familyMember = this.familyMemberMapper.selectFamilyMemberById(userId);
        if (ObjectUtil.isEmpty(familyMember)) {
            throw new BaseException("");
        }
        // 检查关系是否已存在，避免重复绑定
        LambdaQueryWrapper<FamilyMemberElder> existQuery = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<FamilyMemberElder> wrapper = existQuery.eq(FamilyMemberElder::getFamilyMemberId, familyMember.getId())
                .eq(FamilyMemberElder::getElderId, elder.getId());

        if (familyMemberElderMapper.selectCount(wrapper) > 0) {
            throw new BaseException("该家属已绑定此老人");
        }
        //在中间关系表family_member_elder中添加
        this.familyMemberElderMapper.insertFamilyMemberElder(familyMember.getId(), elder.getId(), memberElderDto.getRemark());

    }

    /**
     * 查询已绑定老人列表
     *
     * @param page
     */
    @Override
    public List<MemberElderVo> listByPage(IPage page) {
        //如果page为空，为page设置默认值
        if (ObjectUtil.isEmpty(page)) {
            page.setCurrent(1);
            page.setPages(10);
        }
        //取userid
        Long userId = UserThreadLocal.getUserId();
        //根据userid去中间关系表中查询
        List<FamilyMemberElder> familyMemberElder = familyMemberElderMapper.selectByFamilyId(userId);

        //组装返回的List<MemberElderVo>
        List<MemberElderVo> memberElderVos = new ArrayList<>();
        familyMemberElder.forEach(f -> {
            MemberElderVo memberElderVo = new MemberElderVo();
            //组装老人表部分
            Elder elder = elderMapper.selectElderById(f.getElderId());
            BeanUtil.copyProperties(elder, memberElderVo, "id");
            Bed bed = bedMapper.selectBedById(elder.getBedId());
            Room room = roomMapper.selectRoomById(bed.getRoomId());
            memberElderVo.setTypeName(room.getTypeName());

            // 组装设备部分
            try {
                LambdaQueryWrapper<Device> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(Device::getLocationType, 0)
                        .eq(Device::getBindingLocation, elder.getId());
                Device device = this.deviceMapper.selectOne(lambdaQueryWrapper);
                BeanUtil.copyProperties(device, memberElderVo, "id");
            } catch (Exception e) {
                throw new RuntimeException("有老人尚未绑定随身设备");
            }

            //组装家属部分
            memberElderVo.setMremark(f.getRemark());
            memberElderVo.setMid(String.valueOf(f.getId()));
            memberElderVos.add(memberElderVo);
        });

        return memberElderVos;
    }

    /**
     * 查询家属列表
     *
     * @return
     */
    @Override
    public List<FamilyMemberElder> myPage() {
        Long userId = UserThreadLocal.getUserId();
        List<FamilyMemberElder> familyMemberElderList = this.familyMemberElderMapper.selectByFamilyId(userId);
        familyMemberElderList.forEach(f -> {
            Elder elder = elderMapper.selectElderById(f.getElderId());
            if (ObjectUtil.isEmpty(elder)) {
                throw new BaseException("");
            }
            f.setRemark(elder.getName());
        });
        return familyMemberElderList;
    }

    /**
     * 查询健康数据
     *
     * @param iotId
     */
    @Override
    public List<DevicePropertyStatusInfo> queryServiceProperties(String iotId) {
        //查询deviceDate表
        List<DevicePropertyStatusInfo> propertyInfoList = new ArrayList<>();
        LambdaQueryWrapper<DeviceData> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DeviceData::getIotId, iotId)
                .eq(DeviceData::getLocationType, 0);

        //调用华为云为个别字段赋值queryProductDetail，根据这个设备
        ShowDeviceResponse response = huaweiIotUtil.queryDeviceDetail(iotId);
        String productId = response.getProductId();
        List<ServiceCapability> serviceCapabilities = huaweiIotUtil.queryProductDetail(productId);
        serviceCapabilities.forEach(s -> {
            List<ServiceProperty> properties = s.getProperties();
            properties.forEach(p -> {
                DevicePropertyStatusInfo devicePropertyStatusInfo = new DevicePropertyStatusInfo();
                BeanUtil.copyProperties(p, devicePropertyStatusInfo);
                devicePropertyStatusInfo.setFunctionId(p.getPropertyName());
                devicePropertyStatusInfo.setName(p.getDescription());

                propertyInfoList.add(devicePropertyStatusInfo);
            });
        });
        //获取这个设备的历史数据 todo:: 从redis里面查询
        List<DeviceData> deviceDataList = this.deviceDataMapper.selectList(lambdaQueryWrapper);
        deviceDataList.forEach(d -> {
            LocalDateTime alarmTime = d.getAlarmTime();
            long time = alarmTime.atZone(ZoneId.systemDefault())
                    .toInstant()
                    .toEpochMilli();
            propertyInfoList.forEach(p -> {
                if (ObjectUtil.equal(p.getFunctionId(), d.getFunctionId())) {
                    p.setTime(StrUtil.toString(time));
                    p.setValue(d.getDataValue());
                }
            });
        });
        return propertyInfoList;
    }

    /**
     * 按天统计查询指标数据
     */
    @Override
    public List<DeviceDataGraphVo> queryDeviceDataListByDay(String iotId, String functionId, LocalDateTime startTime,LocalDateTime endTime) {

        return deviceDataMapper.queryDeviceDataListByDay(iotId, functionId, startTime, endTime);
    }

    /**
     * 按天统计查询指标数据
     */
    @Override
    public List<DeviceDataGraphVo> queryDeviceDataListByWeek(String iotId, String functionId, LocalDateTime startTime, LocalDateTime endTime) {
        return deviceDataMapper.queryDeviceDataListByWeek(iotId, functionId, startTime, endTime);
    }


    /**
 * 新增或修改用户
 *
 * @param familyMember
 * @param phone
 */
private void inserOrUpdateFamilyMember(FamilyMember familyMember, String phone) {

    //1. 判断新的手机跟数据库中保存的手机号是否一致
    if (ObjectUtil.notEqual(familyMember.getPhone(), phone)) {
        familyMember.setPhone(phone);
    }

    //2. id是否存在，如存在，就修改
    if (ObjectUtil.isNotEmpty(familyMember.getId())) {
        updateById(familyMember);
        return;
    }

    //3. 不存在，就新增 (拼装用户的昵称：随机字符串+手机号后4位)
    int index = (int) (Math.random() * DEFAULT_NICK_NAME.size());
    String nickName = DEFAULT_NICK_NAME.get(index) + phone.substring(phone.length() - 4);
    familyMember.setName(nickName);
    save(familyMember);

}

/**
 * 查询老人家属
 *
 * @param id 老人家属主键
 * @return 老人家属
 */
@Override
public FamilyMember selectFamilyMemberById(Long id) {
    return getById(id);
}

/**
 * 查询老人家属列表
 *
 * @param familyMember 老人家属
 * @return 老人家属
 */
@Override
public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember) {
    return familyMemberMapper.selectFamilyMemberList(familyMember);
}

/**
 * 新增老人家属
 *
 * @param familyMember 老人家属
 * @return 结果
 */
@Override
public int insertFamilyMember(FamilyMember familyMember) {
    return save(familyMember) ? 1 : 0;
}

/**
 * 修改老人家属
 *
 * @param familyMember 老人家属
 * @return 结果
 */
@Override
public int updateFamilyMember(FamilyMember familyMember) {
    return updateById(familyMember) ? 1 : 0;
}

/**
 * 批量删除老人家属
 *
 * @param ids 需要删除的老人家属主键
 * @return 结果
 */
@Override
public int deleteFamilyMemberByIds(Long[] ids) {
    return removeByIds(Arrays.asList(ids)) ? 1 : 0;
}

/**
 * 删除老人家属信息
 *
 * @param id 老人家属主键
 * @return 结果
 */
@Override
public int deleteFamilyMemberById(Long id) {
    return removeById(id) ? 1 : 0;
}

}
